<template>
  <!-- 轮播图与两侧内容的容器 -->
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20">
    <div class="flex flex-col lg:flex-row gap-8 items-stretch justify-between">
      <!-- 左侧内容 -->
      <div class="w-full lg:w-[26%] space-y-6 flex flex-col h-full">
        <div class="flex items-center gap-2">
          <h3
            class="text-2xl font-bold text-[#C32A31] lg:text-left cursor-pointer hover:text-[#a02228] transition-colors duration-200"
            @click="navigateToCategory('校园快讯')"
            title="点击查看校园快讯分类文章"
          >
            校园快讯
          </h3>
          <span class="text-[#e57373] italic font-medium">Campus News</span>
        </div>

        <!-- 正常显示校园快讯 -->
        <template v-if="campusActivity && !error.campusActivity">
          <div
            class="group relative overflow-hidden flex-grow shadow-lg transition-all duration-300 min-h-[300px] cursor-pointer"
            @click="handleClick,navigateToCategory('校园快讯')"
          >
            <img :src="campusActivity.image" alt="校园快讯"
                 class="w-full h-full object-cover transition-all duration-500 group-hover:scale-110 group-hover:brightness-110" />
            <div class="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
            <div class="absolute bottom-0 left-0 right-0 p-4 text-white transform translate-y-full group-hover:translate-y-0 transition-transform duration-300">
              <p class="text-sm font-medium">点击查看更多校园快讯信息</p>
            </div>
          </div>
          <p class="text-gray-600 text-sm leading-relaxed mt-auto">{{ campusActivity.description }}</p>
        </template>



      </div>

      <!-- 中间轮播图 -->
      <div class="w-full lg:w-[40%] lg:px-2 relative z-10 no-border">
        <swiper
            :style="{
            '--swiper-navigation-color': '#C32A31',
            '--swiper-pagination-color': '#C32A31',
          }"
            :speed="600"
            :parallax="true"
            :pagination="{
            clickable: true,
          }"
            :navigation="true"
            :modules="modules"
            class="mySwiper2 overflow-hidden shadow-lg rounded-md no-border"
        >
          <!-- 背景图 -->
          <div
              slot="container-start"
              class="parallax-bg"
              :style="{
                'background-image': middleSlides.length > 0 ?
                  `url(${middleSlides[0].backgroundImage})` : '',
              }"
              data-swiper-parallax="-23%"
          ></div>

          <swiper-slide v-for="slide in middleSlides" :key="slide.id" class="hover-zoom">
            <div class="title" data-swiper-parallax="-300">{{ slide.title }}</div>
            <div class="subtitle" data-swiper-parallax="-200">{{ slide.subtitle }}</div>
            <div class="text" data-swiper-parallax="-100">
              <p>{{ slide.content }}</p>
            </div>
          </swiper-slide>
        </swiper>
      </div>

      <!-- 右侧内容 -->
      <div class="w-full lg:w-[26%] space-y-6 flex flex-col h-full lg:pl-2 relative z-20">
        <div class="flex items-center gap-2">
          <h3
            class="text-2xl font-bold text-[#C32A31] lg:text-left cursor-pointer hover:text-[#a02228] transition-colors duration-200"
            @click="navigateToCategory('学术活动')"
            title="点击查看学术活动分类文章"
          >
            学术活动
          </h3>
          <span class="text-[#e57373] italic font-medium">Academic Research</span>
        </div>

        <!-- 正常显示学术活动 -->
        <template v-if="academicResearch && !error.academicResearch">
          <div
            class="group relative overflow-hidden flex-grow shadow-lg transition-all duration-300 min-h-[300px] border border-transparent cursor-pointer"
            @click="handleClick,navigateToCategory('学术活动')"
          >
            <img :src="academicResearch.image" alt="学术活动"
                 class="w-full h-full object-cover transition-all duration-500 group-hover:scale-110 group-hover:brightness-110"
                 style="aspect-ratio: 1/1; object-position: center;" />
            <div class="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
            <div class="absolute bottom-0 left-0 right-0 p-4 text-white transform translate-y-full group-hover:translate-y-0 transition-transform duration-300">
              <p class="text-sm font-medium">点击查看更多学术活动信息</p>
            </div>
          </div>
          <p class="text-gray-600 text-sm leading-relaxed mt-auto">{{ academicResearch.description }}</p>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Navigation, Pagination, Parallax } from "swiper/modules";
import axios from 'axios';

// Import Swiper styles
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/parallax';

// 导入API配置
import { homeApi, API_BASE_URL } from '@/utils/api';

// Vue Router实例
const router = useRouter();

// 定义emit
const emit = defineEmits(['api-error'])

// 定义模块变量，包含所有需要的Swiper模块
const modules = [Navigation, Pagination, Parallax];

// 中间轮播图数据
const middleSlides = ref([]);
const campusActivity = ref(null);
const academicResearch = ref(null);

const error = ref({
  middleSlides: null,
  campusActivity: null,
  academicResearch: null
});

// 获取中间轮播图数据
const fetchMiddleSlides = async () => {
  error.value.middleSlides = null;
  try {
    const response = await homeApi.getMiddleCarouselData();
    
    // 处理API返回的不同数据结构
    let slidesData = [];
    if (Array.isArray(response)) {
      slidesData = response;
    } else if (response && response.data && Array.isArray(response.data)) {
      slidesData = response.data;
    } else if (response && response.slides && Array.isArray(response.slides)) {
      slidesData = response.slides;
    } else {
      throw new Error('API返回的数据格式不正确');
    }

    middleSlides.value = slidesData.map(slide => ({
      id: slide.id || slide.slide_id,
      title: slide.title || '',
      subtitle: slide.subtitle || '',
      content: slide.content || '',
      backgroundImage: slide.background_image || slide.backgroundImage || ''
    }));

    // 如果没有数据，显示错误信息
    if (middleSlides.value.length === 0) {
      error.value.middleSlides = '暂无轮播图数据';
      middleSlides.value = [];
    }
  } catch (err) {
    console.error('Error fetching middle slides:', err);
    // 触发API错误事件，让父组件处理
    emit('api-error', err);
  }
};

    // 获取校园快讯数据
const fetchCampusActivity = async () => {
  error.value.campusActivity = null;
  try {
    const response = await homeApi.getCampusHighlights();
    
    // 处理API返回的不同数据结构
    let highlightsData = [];
    if (Array.isArray(response)) {
      highlightsData = response;
    } else if (response && response.data && Array.isArray(response.data)) {
      highlightsData = response.data;
    } else if (response && response.highlights && Array.isArray(response.highlights)) {
      highlightsData = response.highlights;
    } else {
      throw new Error('API返回的校园快讯数据格式不正确');
    }

    if (highlightsData.length > 0) {
      const highlight = highlightsData[0];
      campusActivity.value = {
        image: highlight.image_url || highlight.image || '',
        description: highlight.description || highlight.title || '校园快讯'
      };
    } else {
      error.value.campusActivity = '暂无校园快讯数据';
      campusActivity.value = null;
    }
  } catch (err) {
    console.error('Error fetching campus activity:', err);
    error.value.campusActivity = '获取校园快讯数据失败';
    campusActivity.value = null;
    // 触发API错误事件，让父组件处理
    emit('api-error', err);
  }
};

// 获取学术研究数据
    const fetchAcademicResearch = async () => {
        error.value.academicResearch = null;
        try {
            // 暂时使用静态数据，后续可以添加对应的API端点
            // const response = await homeApi.getAcademicResearch();

            // 使用静态数据
            academicResearch.value = {
                image: '/images/academic-research.jpg',
                description: '学院致力于产学研结合，推动科技创新发展'
            };
        } catch (err) {
            console.error('Error fetching academic research:', err);
            // 触发API错误事件，让父组件处理
            emit('api-error', err);
        }
    };

// 导航到分类搜索页面
const navigateToCategory = (category) => {
  router.push({
    path: '/search',
    query: {
      category: category
    }
  });

  //  滚动到顶部
    window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};

// 页面加载时获取数据
onMounted(async () => {
  try {
    // 不预设默认数据，直接从API获取
    middleSlides.value = [];
    campusActivity.value = null;
    academicResearch.value = null;

    // 尝试从 API 获取数据
    await Promise.all([
      fetchMiddleSlides(),
      fetchCampusActivity(),
      fetchAcademicResearch()
    ]);
  } catch (error) {
    console.error('Error in onMounted:', error);
  }
});


</script>

<style scoped>
/* 轮播图样式 - 保留必要的样式 */
.mySwiper2 {
  height: 100%;
  min-height: 500px;
  position: relative;
  border: none !important;
  outline: none !important;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05) !important;
}

/* 添加无边框类 */
.no-border {
  border: none !important;
  outline: none !important;
}

/* 覆盖Swiper组件的默认边框样式 */
.swiper,
.swiper-wrapper,
.swiper-slide,
.swiper-container {
  border: none !important;
  outline: none !important;
}

/* 覆盖鼠标悬停状态 */
.mySwiper2:hover,
.mySwiper2:focus,
.mySwiper2:active {
  border: none !important;
  outline: none !important;
}

.mySwiper2 .swiper-slide {
  font-size: 18px;
  color: #fff;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  padding: 40px 60px;
  transition: transform 0.5s ease;
}

/* 鼠标悬停时的放大效果 */
.mySwiper2 .swiper-slide.hover-zoom:hover {
  transform: scale(1.03);
  border: none !important;
  outline: none !important;
}

.mySwiper2 .parallax-bg {
  position: absolute;
  left: 0;
  top: 0;
  width: 130%;
  height: 100%;
  -webkit-background-size: cover;
  background-size: cover;
  background-position: center;
  filter: brightness(0.6); /* 降低背景亮度，使文字更清晰 */
  border-radius: 0.375rem; /* 添加圆角，与外层容器保持一致 */
  border: none !important;
  outline: none !important;
}

.mySwiper2 .title {
  font-size: 36px;
  font-weight: 700;
  margin-bottom: 10px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}

.mySwiper2 .subtitle {
  font-size: 20px;
  margin-bottom: 20px;
  text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.5);
}

.mySwiper2 .text {
  font-size: 16px;
  max-width: 800px;
  line-height: 1.6;
  background-color: rgba(0, 0, 0, 0.4);
  padding: 15px;
  backdrop-filter: blur(2px);
}

/* 响应式调整 - 使用 Tailwind CSS 的响应式类 */
@media (max-width: 1024px) {
  .mySwiper2 {
    height: 450px;
  }
}

@media (max-width: 768px) {
  .mySwiper2 {
    height: 400px;
  }
}

/* 添加一个清除浮动的类 */
.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
</style>
